package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityJingYingSearchBinding;
import com.sgb.kjwl.interfaces.RecyclerClick;
import com.sgb.kjwl.model.entity.manage.TheEnterpriseOfEntity;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.manage.RecommendedEnterprisesAdapter;
import com.sgb.kjwl.viewmodel.manage.JingYingSearchModel;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class JingYingSearchActivity extends AppActivity {

    JingYingSearchModel model;
    private ActivityJingYingSearchBinding binding;

    private TagAdapter historyAdapter;
    private RecommendedEnterprisesAdapter adapter;
    private boolean mIsLoadMore = false;
    private int mPage;
    private String keyWork = "";

    private String longitude;
    private String latitude;
    private Timer timer = new Timer();
    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, JingYingSearchActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        model = new ViewModelProvider(this).get(JingYingSearchModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jing_ying_search);
        binding.setViewModel(model);
        binding.llBar.ivBack.setOnClickListener(this);
        binding.llBar.tvSearch.setOnClickListener(this);
        binding.llHistoryRecord.ivDelete.setOnClickListener(this);
        binding.llBar.ivDeleteEdit.setOnClickListener(this);
        initEdit();
        initLiveData();
        initRecyclerView();
        longitude = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        latitude = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        timer.schedule(new RemindTask(),300);
        binding.llBar.editSearch.requestFocus();
    }

    class RemindTask extends TimerTask {
        public void run() {
            //打开页面默认显示软键盘
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(binding.llBar.editSearch, InputMethodManager.RESULT_SHOWN);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
            timer.cancel();
        }
    }

    private void initRecyclerView() {
        adapter = new RecommendedEnterprisesAdapter(getActivity(), null);
        binding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClick(new AdapterOnItemClick<TheEnterpriseOfEntity>() {
            @Override
            public void onItemClick(TheEnterpriseOfEntity entity, int position) {
                if (!TextUtils.isEmpty(entity.getSupplier())) {
                    WebsiteInfoActivity.start(getActivity(), entity.getSupplier(), 1);
                } else {
                    Toast.makeText(getActivity(), "公司no为空", Toast.LENGTH_SHORT).show();
                }
            }
        });

        adapter.setmRecyclerClick(new RecyclerClick<TheEnterpriseOfEntity>() {
            @Override
            public void followClick(TheEnterpriseOfEntity entity) {
                if (DialogHelper.checkLogin()) {
                    if (entity.getFollow()) {
                        DialogHelper.showDialog(JingYingSearchActivity.this, "提示", "确定取消关注该企业？", "取消关注", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                model.follow(entity.getSupplier());
                            }
                        });
                    } else {
                        model.follow(entity.getSupplier());
                    }
                } else {
                    VerificationCodeLoginActivity.start(JingYingSearchActivity.this, EventConstant.EVENT_MANAGE);
                }
            }
        });

        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadComData(false);
            }

            @Override
            public void onLoadMore() {
                loadComData(true);
            }
        });
    }

    private void loadComData(boolean isLoadMore) {
        Map<String, Object> map = new HashMap<>();
        this.mIsLoadMore = isLoadMore;
        mPage = !isLoadMore ? 1 : mPage + 1;
        map.put("page", mPage);
        map.put("limit", "20");
        map.put("onMap", "0");
        map.put("name", keyWork);
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        model.getComList(map, this);
    }


    private void initEdit() {
        binding.llBar.editSearch.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                search();
                return true;
            }
            return false;
        });
    }

    private void initLiveData() {
        model.historyRecordLD.observe(this, strings ->{
            setSearchHistoryData(strings);
        });
        model.isSuccessFllowLD.observe(this, b -> {
            loadComData(false);
        });
        model.msgLD.observe(this, msg -> {
            MToast.showLongToast(this, msg);
        });
        model.companyListLD.observe(this, datas -> {//返回列表数据
            binding.recyclerView.refreshComplete();
            if (mIsLoadMore) {
                if (null != datas && datas.size() > 0) {
                    binding.recyclerView.loadMoreComplete();
                    adapter.addDatas(datas);
                } else {
                    binding.recyclerView.setNoMore(true);
                }
                binding.recyclerView.setVisibility(View.VISIBLE);
            } else {
                binding.recyclerView.refreshComplete();
                if (null != datas && datas.size() > 0) {
                    binding.recyclerView.setVisibility(View.VISIBLE);
                    binding.emptyView.setVisibility(View.GONE);
                    adapter.setDatas(datas);
                    binding.recyclerView.setLoadingMoreEnabled(true);
                } else {
                    adapter.setDatas(null);
                    binding.recyclerView.setVisibility(View.GONE);
                    binding.emptyView.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    @Override
    protected void init() {
        model.getSearchHistoryListData();
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                search();
                break;
            case R.id.iv_delete:
                cleanHistoryWord();
                break;
            case R.id.iv_delete_edit:
                keyWork = "";
                binding.llBar.editSearch.setText("");
                binding.llHistoryRecord.llSearchRecord.setVisibility(View.VISIBLE);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.GONE);
                model.getSearchHistoryListData();
                closeKeybord();
                break;
        }
    }

    /**
     * 清除本地搜索记录
     */
    private void cleanHistoryWord() {
        MkvUtils.get().putString(MkvUtils.CommomData, CacheMarker.JY_SEARCH_HISTORY_RECORD, "");
        model.getSearchHistoryListData();
    }

    private void search() {
        keyWork = binding.llBar.editSearch.getText().toString().trim();
        if (TextUtils.isEmpty(keyWork)) {
            MToast.showToast(this, "请输入关键字");
        } else {
            binding.llHistoryRecord.llSearchRecord.setVisibility(View.GONE);
            binding.recyclerView.setVisibility(View.VISIBLE);
            loadComData(false);
            model.recordsLocal(keyWork);
        }
    }

    /**
     * 设置历史搜索词汇
     */
    public void setSearchHistoryData(List<String> ls) {
        if (ls == null || ls.size() == 0) {
            binding.llHistoryRecord.tvNoSearch.setVisibility(View.VISIBLE);
            binding.llHistoryRecord.ivDelete.setVisibility(View.GONE);
        } else {
            binding.llHistoryRecord.tvNoSearch.setVisibility(View.GONE);
            binding.llHistoryRecord.ivDelete.setVisibility(View.VISIBLE);
        }

        historyAdapter = new TagAdapter<String>(ls) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                LinearLayout layout = (LinearLayout) LayoutInflater.from(JingYingSearchActivity.this)
                        .inflate(R.layout.item_zulin_search_words, binding.llHistoryRecord.searchHistoryList, false);
                TextView tv = layout.findViewById(R.id.name);
                tv.setText(s);
                return layout;
            }
        };
        binding.llHistoryRecord.searchHistoryList.setAdapter(historyAdapter);
        binding.llHistoryRecord.searchHistoryList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                keyWork = ls.get(position);
                model.recordsLocal(keyWork);
                binding.llBar.editSearch.setText(keyWork);
                binding.llHistoryRecord.llSearchRecord.setVisibility(View.GONE);
                binding.recyclerView.setVisibility(View.VISIBLE);
                loadComData(false);
                return true;
            }
        });
    }


}
